<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div>
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :data="formData" @submit="onSubmit" :rules="rules" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="6">
            <t-card class="step-card" size="small" title="基本信息">
              <t-form-item label="投入时间：" name="year">
                <t-date-picker style="width: 390px"  v-model="formData.year"></t-date-picker>
              </t-form-item>
              <t-form-item label="自筹投入（万元）：" name="zcBudget">
                <t-input-number style="width: 390px" clearable v-model="formData.zcBudget"></t-input-number>
              </t-form-item>
              <t-form-item label="上级拨款（万元）：" name="tbBudget">
                <t-input-number style="width: 390px" clearable v-model="formData.tbBudget"></t-input-number>
              </t-form-item>
              <t-form-item label="备注：" name="note">
                <t-input style="width: 390px" clearable v-model="formData.note"></t-input>
              </t-form-item>
            </t-card>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="12" class="query-form-inline">
              <t-button :loading="subBtnLoading" theme="primary" @click="subType=2"  type="submit">提交</t-button>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { getDictList } from "@/api/system/dict/data";
import {getFiles} from "@/api/common";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";

import FileUpload from "@/components/FileUpload/index.vue"
import { TODAY } from '@/utils/date';
import dayjs from "dayjs";

export default {
  name: "draft-review",
  components: {
    TinyMceEditor,
    FileUpload
  },
  dicts: ["formulate_type","standard_category","standard_property"],
  data() {
    return {
      subBtnLoading:false,
      reviseNumDisable:true,
      active:1,
      subType:2,
      projectFileData: [
        {
          id: 1,
          c1: "立项公文（盖章原件）",
          c2: "是",
          moduleKey: "projectLXGW",
          fileIds: [],
          fileLists: [],
        },
        {
          id: 2,
          c1: "标准草案",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZCA"
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      deptMenuOptions: [],
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0
      },
      tinymceFlag: 1,
      dayjs,
      formData: {
        id: this.$route.params.id,
        platformId:this.$route.query.platformId,
        inputDate: '',
        zcBudget: '',
        tbBudget: '',
        note: '',
      },
      rules: {
        year: [
          {
            required: true,
            message: "投入时间不能为空",
          },
        ],
        zcBudget: [
          {
            required: true,
            message: "自筹投入（万元）不能为空",
          },
        ],
        tbBudget: [
          {
            required: true,
            message: "上级拨款（万元）不能为空",
          },
        ],
      },
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.$api.bzh.standard.detailById(this.$route.query.id).then(response => {
        getFiles(this.$route.query.id).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData[0].fileLists = files.projectLXGW || [];
          this.projectFileData[1].fileLists = files.projectBZCA || [];
          this.projectFileData[0].fileIds = files.projectLXGW?.map(val => val.id) || [];
          this.projectFileData[1].fileIds = files.projectBZCA?.map(val => val.id) || [];
        }).catch((e) => {
          this.$message.error(e.toString());
        });
        Object.assign(this.formData, response.data)
      }).catch(e => {
        this.$message.error(e.toString())
      })
    }

  },
  async created() {
    await this.getDeptTreeSelect(this.$store.state.user.deptId)
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增

  },
  methods: {
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    filterByTree(val, tree, children = "children", id = "id", label = "label") {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label]
          } else if (item[children]) {
            return convert(item[children])
          }
          return false
        })
      }
      convert(tree)
      return text
    },
    onSubmit({ validateResult, firstError }) {
      if ( validateResult === true) {
        // 路由有id修改，没有新增
        if (this.isEdit) {
          const message = "修改成功"
          this.subBtnLoading = true
          this.$api.tjpt.budget.edit(this.formData).then(response => {
            this.subBtnLoading =false
            this.$message.success(message)
            this.$router.push("/tjpt/runManagement/funding-my")
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })
        } else {
          const message = "提交成功"
          this.subBtnLoading = true
          this.$api.tjpt.budget.add(this.formData).then(response => {
            this.subBtnLoading =false
            this.$message.success(message)
            this.$emit("reload")
            this.$router.push("/tjpt/runManagement/funding-my")
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })
        }
      } else {
        this.subBtnLoading =false
        this.$message.error(firstError)
      }

    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>

